# ================================================
# 
# http://www.checknerds.com
# 
# Original Author: CNBorn, http://cnborn.net, 2009
# 
#
# ================================================

import sys
from ConfigParser import ConfigParser
import os

import datetime
import hashlib
import urllib
import httplib

class checknerdsValidator():
	def __init__(self):
		self.userid = 0
		self.userkey = ""

		self.appid = 0
		self.servicekey = "" 

		self.sentkey = ""
		self.sentuserkey = ""

		self.baseurl = ""

		self.debug_mode = 0
		self.debug_userid = 0
		self.debug_userkey = ""
		self.debug_appid = 0
		self.debug_servicekey = ""

		self.headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}


		pass

	def __init_conn__(self):
		return httplib.HTTPConnection(self.baseurl)

	def __init_params__(self):
		#return urllib.urlencode({'apiappid':self.appid, 'servicekey':self.sentkey, 'apiuserid':self.userid, 'apikey':self.sentuserkey , 'userid': userid })
		return {'apiappid':self.appid, 'servicekey':self.sentkey, 'apiuserid':self.userid, 'apikey':self.sentuserkey}
		#return basicpara

	def validate(self, appid, servicekey):

		#if the parameter is not given, check whether they are in the .checknerds debug section
		#(which should be read from ParseConfigfromFile)
		if not appid:
			if self.appid != 0:
				pass
		else:
			self.appid = appid
			self.servicekey = servicekey
		
		self.sentkey = hashlib.sha256(self.servicekey).hexdigest() 
		self.sentuserkey = hashlib.sha256(self.userkey).hexdigest()

	def get_friends(self, userid):
		conn = self.__init_conn__
		
		params = urllib.urlencode(self.__init_params__)

		conn.request("POST", "http://" + self.baseurl + "/service/friends/", params, self.headers)
		response = conn.getresponse()
		data = response.read()
		conn.close()

		return data

	def get_useritems(self, userid):
		conn = httplib.HTTPConnection(self.baseurl)
		params = urllib.urlencode({'apiappid':self.appid, 'servicekey':self.sentkey, 'apiuserid':self.userid, 'apikey':self.sentuserkey , 'userid': userid})

		#print params
		conn.request("POST", "http://" + self.baseurl + "/service/item/", params, self.headers)
		response = conn.getresponse()
		data = response.read()
		conn.close()
		#print data
		edata = eval(data)
		return edata

	def get_items(self, done=False, routine='none', public='none', maxitems=15):
		conn = self.__init_conn__()
		urlpara = self.__init_params__()

		urlpara['userid'] = self.userid #temp
		urlpara['done'] = done
		urlpara['routine'] = routine
		urlpara['public'] = public
		urlpara['maxitems'] = maxitems

		params = urllib.urlencode(urlpara)

		conn.request("POST", "http://" + self.baseurl + "/service/item/", params, self.headers)
		response = conn.getresponse()
		data = response.read()
		conn.close()
		#print data
		if len(data) != 0:
			edata = eval(data)
			return edata
		else:
			return None


	def add_item(self, name, comment="", routine="none", public="public", date="", tags=""):
		conn = self.__init_conn__()
		urlpara = self.__init_params__()

		urlpara['name'] = name
		urlpara['comment'] = comment
		urlpara['routine'] = routine
		urlpara['public'] = public
		urlpara['date'] = date
		urlpara['tags'] = tags
		
		params = urllib.urlencode(urlpara)

		conn.request("POST", "http://" + self.baseurl + "/service/additem/", params, self.headers)
		response = conn.getresponse()
		data = response.read()
		conn.close()

		print data
		#edata = eval(data)
		return data
	



	def get_user(self, userid):
		conn = self.__init_conn__()
		urlpara = self.__init_params__()

		urlpara['userid'] = userid
		params = urllib.urlencode(urlpara)

		conn.request("POST", "http://" + self.baseurl + "/service/user/", params, self.headers)
		response = conn.getresponse()
		data = response.read()
		conn.close()

		userdata = eval(data)
		return userdata


	def getConfigFromFile(self, filename):

		if not filename:
			filename = os.path.join(os.environ['HOME'], '.checknerds')
		
		config = ConfigParser()
		config.read([filename])

		self.baseurl = config.get('base', 'base_url')
		if self.baseurl == None:
			self.baseurl = "www.checknerds.com"

		self.userid = config.get('base', 'userid')
		if self.userid == None:
			#userid = raw_input("Please input your CheckNerds userid:")
			pass

		self.userkey = config.get('base', 'userkey')
		if self.userkey == None:
			#userkey = getpass.getpass("Please input your API key:")
			pass

		#Get Debug information
		self.debug_mode = config.get('base', 'debug')
		if self.debug_mode == '1':				
			self.debug_baseurl = config.get('base', 'debug_base_url')
			if self.debug_baseurl != None:
				self.baseurl = self.debug_baseurl

			self.debug_userid = config.get('base', 'debug_userid')
			if self.debug_userid != None:
				self.userid = self.debug_userid

			self.debug_userkey = config.get('base', 'debug_userkey')
			if self.debug_userkey != None:
				self.userkey = self.debug_userkey

			self.debug_appid = config.get('base', 'debug_appid')
			if self.debug_appid != None:
				self.appid = self.debug_appid
			self.debug_servicekey = config.get('base', 'debug_service392key')
			if self.debug_servicekey != None:
				self.servicekey = self.debug_servicekey

		self.sentkey = hashlib.sha256(self.servicekey).hexdigest() 
		self.sentuserkey = hashlib.sha256(self.userkey).hexdigest()
